package tc.alert.tckejisoc.pool;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数：根据CPU核心数动态设置
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors() + 1);
        executor.setMaxPoolSize(20); // 最大线程数
        executor.setQueueCapacity(200); // 队列容量
        executor.setKeepAliveSeconds(30); // 线程空闲时间
        executor.setThreadNamePrefix("custom-executor-"); // 线程名前缀
        // 拒绝策略：由提交任务的线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 允许核心线程超时（可选）
        executor.setAllowCoreThreadTimeOut(true);
        executor.initialize(); // 初始化线程池
        return executor;
    }
}